<template>
  <div class="friend-apply-list">
    <div class="apply-header" @click="toggleExpand">
      <div class="header-left">
        <el-icon><Message /></el-icon>
        <span>好友申请</span>
        <div v-show="friendApplyCount > 0" class="apply-badge">{{ friendApplyCount }}</div>
      </div>
      <el-icon :class="{'is-rotate': isExpanded}"><ArrowDown /></el-icon>
    </div>
    <div class="apply-content" :class="{'expanded': isExpanded}">
      <el-scrollbar class="apply-scrollbar" ref="scrollbar" @scroll="handleScroll">
        <el-empty v-if="applyList.length === 0" description="暂无好友申请"></el-empty>
        <div v-else class="apply-items">
          <div v-for="item in displayList" :key="item.id" class="apply-item">
            <div class="user-info">
              <head-image :url="item.fromHeadImage" :name="item.fromNickName || '未知用户'" :size="40"></head-image>
              <div class="info-content">
                <div class="nickname">{{ item.fromNickName || '未知用户' }}</div>
                <div class="apply-message" v-if="item.reason">
                  <el-tooltip v-if="item.reason.length > 20" :content="item.reason" placement="top">
                    <span>{{ item.reason.substring(0, 20) }}...</span>
                  </el-tooltip>
                  <span v-else>{{ item.reason }}</span>
                </div>
                <div class="apply-time">{{ $date.toTimeText(item.createTime) }}</div>
              </div>
            </div>
            <div class="action-column">
              <div v-if="item.applyStatus === 0" class="apply-actions">
                <el-dropdown trigger="click" @command="(command) => handleApply(item, command)">
                  <el-button type="primary" size="small">
                    <el-icon><Operation /></el-icon>
                    操作
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="agree">
                        <el-icon><Check /></el-icon>同意
                      </el-dropdown-item>
                      <el-dropdown-item command="refused" divided>
                        <el-icon><Close /></el-icon>拒绝
                      </el-dropdown-item>
                      <el-dropdown-item command="ignore" divided>
                        <el-icon><CircleClose /></el-icon>忽略
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div v-else class="apply-status">
                {{ getStatusText(item.applyStatus) }}
              </div>
            </div>
          </div>
        </div>
        <div v-if="loading" class="loading-more">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-if="!hasMore && displayList.length > 0" class="no-more">
          没有更多数据了
        </div>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import HeadImage from '../common/HeadImage.vue'
import { formatDateTime } from '@/api/date.js'

export default {
  name: 'FriendApplyList',
  components: {
    HeadImage
  },
  data() {
    return {
      applyList: [],
      displayList: [], // 用于分页显示的列表
      isExpanded: false,
      pageParams: {
        pageNum: 1,
        pageSize: 10
      },
      hasMore: true,
      total: 0,
      loading: false
    }
  },
  computed: {
    friendApplyCount() {
      return this.$store.state.friendStore.friendApplyCount;
    },
    userInfo() {
      return this.$store.state.userStore.userInfo;
    },
    applyMessage() {
      return this.$store.state.chatStore.applyMessage;
    }
  },
  created() {
    this.loadApplyList()
  },
  methods: {
    formatTime(time) {
      return formatDateTime(time)
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
      if(this.isExpanded){
        this.readApplyMessage();
      }
    },
    loadApplyList() {
      const params = {
        pageNo: this.pageParams.pageNum,
        pageSize: this.pageParams.pageSize,
        nickName: '', 
        userId: this.userInfo.id,
        content: '',
        type: 1,
        //applySource: 4
      }
      this.$http({
        url: '/im/apply/page',
        method: 'GET',
        params: {
          ...params,
          status: 0  // 只查询未处理的申请来计算未读数
        }
      }).then(res => {
        if (res && Array.isArray(res.list)) {
          this.applyList = res.list;
          this.total = res.total || 0;
          this.displayList = this.applyList.slice(0, this.pageParams.pageSize);
          this.hasMore = this.displayList.length < this.total;
          
          // 如果有数据，自动展开列表
          if (this.applyList.length > 0) {
            this.isExpanded = true;
          }
        } else {
          this.applyList = [];
          this.displayList = [];
          this.total = 0;
          this.hasMore = false;
        }
      }).catch(error => {
        this.$message.error('加载好友申请列表失败，请稍后重试');
        this.applyList = [];
        this.displayList = [];
        this.total = 0;
        this.hasMore = false;
      });
    },
    getStatusText(status) {
      const statusMap = {
        1: '已同意',
        2: '已拒绝',
        3: '已忽略'
      }
      return statusMap[status] || '未知状态'
    },
    handleApply(item, action) {
      console.log('处理好友申请:', item, action); // 添加日志帮助调试
      
      const actionMap = {
        'agree': {url: '/agree', status: 1, message: '已同意好友申请'},
        'refused': {url: '/refused', status: 2, message: '已拒绝好友申请'},
        'ignore': {url: '/ignore', status: 3, message: '已忽略好友申请'}
      }

      const actionInfo = actionMap[action]
      if (!actionInfo) {
        console.error('未知的操作类型:', action);
        return;
      }
      
      this.$http({
        url: `/im/apply${actionInfo.url}`,
        method: 'POST',
        data: {
          applyId: item.id
        }
      }).then(() => {
        item.applyStatus = actionInfo.status;
        this.$message({
          message: actionInfo.message,
          type: 'success'
        });
        
        // 如果是同意好友申请，需要立即刷新好友列表
        if (action === 'agree') {
          this.$store.dispatch('loadFriend').then(() => {
            // 通知父组件重新加载数据
            this.$emit('refresh-friend-list');
          }).catch(err => {
            console.error('刷新好友列表失败:', err);
          });
        }

        // 标记为已读
        this.$http({
          url: '/message/private/readeApplyMsg',
          method: 'PUT'
        }).then(() => {
          // 重置未读计数
          this.$store.commit('resetFriendApplyCount');
          // 重新加载列表
          this.loadApplyList();
        });
      }).catch(error => {
        console.error('处理好友申请失败:', error);
        this.$message.error('操作失败，请重试');
      });
    },
    readApplyMessage(){//读取未读消息
      if (!this.applyMessage || !this.applyMessage.fids) {
        return;
      }
      
      this.$http({
        url: '/message/private/readeApplyMsg',
        method: 'PUT',
        data: {ids: this.applyMessage.fids || []}
      }).then(() => {
        // 重置未读计数
        this.$store.commit('resetFriendApplyCount');
        // 重新加载列表
        this.loadApplyList();
      }).catch(error => {
        console.error('标记好友申请为已读失败:', error);
      });
    },
    handleScroll() {
      if (!this.$refs.scrollbar || !this.$refs.scrollbar.wrap) {
        return;
      }
      
      const scrollbar = this.$refs.scrollbar.wrap;
      const scrollHeight = scrollbar.scrollHeight;
      const scrollTop = scrollbar.scrollTop;
      const clientHeight = scrollbar.clientHeight;
      
      // 当滚动到距离底部50px时加载更多
      if (scrollHeight - scrollTop - clientHeight < 50 && !this.loading && this.hasMore) {
        this.loadMore();
      }
    },
    loadMore() {
      if (this.loading || !this.hasMore) return;
      
      this.loading = true;
      
      // 获取下一页数据
      this.pageParams.pageNum++;
      
      const params = {
        pageNo: this.pageParams.pageNum,
        pageSize: this.pageParams.pageSize,
        nickName: '', 
        userId: this.userInfo.id,
        content: '',
        type: 1
      };
      
      this.$http({
        url: '/im/apply/page',
        method: 'GET',
        params
      }).then(res => {
        if (res && Array.isArray(res.list) && res.list.length > 0) {
          // 添加新数据到现有列表
          this.applyList = [...this.applyList, ...res.list];
          this.displayList = this.applyList;
          this.total = res.total || 0;
          this.hasMore = this.displayList.length < this.total;
        } else {
          this.hasMore = false;
        }
      }).catch(error => {
        console.error('加载更多好友申请失败:', error);
        this.$message.error('加载更多数据失败，请重试');
      }).finally(() => {
        this.loading = false;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.friend-apply-list {
  background: #fff;
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  
  .apply-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    border-bottom: 1px solid var(--el-border-color-lighter);
    
    &:hover {
      background-color: var(--el-fill-color-light);
    }
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;
      position: relative;
      
      .el-icon {
        color: var(--el-color-primary);
        font-size: 18px;
      }
      
      span {
        font-size: 14px;
        font-weight: 500;
        color: var(--el-text-color-primary);
      }
      
      .apply-badge {
        position: absolute;
        right: -20px;
        top: -8px;
        background-color: var(--el-color-danger);
        color: white;
        border-radius: 10px;
        padding: 0 6px;
        font-size: 12px;
        line-height: 16px;
        min-width: 16px;
        text-align: center;
      }
    }
    
    .el-icon {
      font-size: 14px;
      color: var(--el-text-color-secondary);
      transition: transform 0.3s ease;
      
      &.is-rotate {
        transform: rotate(180deg);
      }
    }
  }
  
  .apply-content {
    max-height: 0;
    overflow: hidden;
    transition: all 0.3s ease-in-out;
    
    &.expanded {
      max-height: 400px;
    }
    
    .apply-scrollbar {
      height: auto;
      max-height: 400px;
      
      :deep(.el-scrollbar__wrap) {
        overflow-x: hidden;
      }
    }
    
    .apply-items {
      .apply-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 16px;
        border-bottom: 1px solid var(--el-border-color-lighter);
        transition: all 0.3s ease;
        
        &:hover {
          background-color: var(--el-fill-color-light);
        }
        
        &:last-child {
          border-bottom: none;
        }
        
        .user-info {
          display: flex;
          align-items: center;
          flex: 1;
          min-width: 0;
          gap: 12px;
          
          .info-content {
            flex: 1;
            min-width: 0;
            
            .nickname {
              font-size: 14px;
              font-weight: 500;
              color: var(--el-text-color-primary);
              margin-bottom: 4px;
              line-height: 1.4;
            }
            
            .apply-message {
              font-size: 13px;
              color: var(--el-text-color-regular);
              margin-bottom: 4px;
              line-height: 1.4;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            
            .apply-time {
              font-size: 12px;
              color: var(--el-text-color-secondary);
              line-height: 1.4;
            }
          }
        }
        
        .action-column {
          margin-left: 16px;
          flex-shrink: 0;
          min-width: 80px;
          
          .apply-actions {
            .el-button {
              padding: 8px 16px;
              transition: all 0.3s ease;
              
              .el-icon {
                margin-right: 4px;
                font-size: 14px;
              }
              
              &:hover {
                transform: translateY(-1px);
                box-shadow: 0 2px 8px rgba(var(--el-color-primary-rgb), 0.2);
              }
            }
          }
          
          .apply-status {
            color: var(--el-text-color-secondary);
            font-size: 13px;
            text-align: right;
            padding: 6px 0;
          }
        }
      }
    }
    
    .loading-more {
      padding: 12px 0;
      text-align: center;
      color: var(--el-text-color-secondary);
      font-size: 13px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      
      .loading-icon {
        animation: rotating 2s linear infinite;
      }
    }
    
    @keyframes rotating {
      from { transform: rotate(0deg); }
      to { transform: rotate(360deg); }
    }
    
    .no-more {
      padding: 12px 0;
      text-align: center;
      color: var(--el-text-color-secondary);
      font-size: 13px;
    }
    
    .el-empty {
      padding: 24px 0;
    }
  }
}

:deep(.el-dropdown-menu) {
  padding: 4px 0;
  
  .el-dropdown-menu__item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    font-size: 13px;
    
    .el-icon {
      margin-right: 8px;
      font-size: 14px;
    }
    
    &:hover {
      background-color: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
    
    &.divided {
      border-top: 1px solid var(--el-border-color-lighter);
    }
  }
}
</style> 